<?php
namespace app\controllers\crontab;
use Yii;
use app\components\redis\RedisMarketingEmail;
use app\components\msgcenter\MsgCenter;
use app\models\marketing\MailGroup;

class EmailExceptionMonitorController  extends \app\base\Controller
{
    public $enableCsrfValidation = false; 
    private $warningThreshold = 8; 
    /**
     * 监控当前redis中子分组进程数量
     */
    public function actionMonitorProductionSubgroupProgressNums()
    {
        $redisMarketingEmail = new RedisMarketingEmail();
        // 查看redis中切割子分组的进程数
        $procedureProgressNums = $redisMarketingEmail->get('procedure_progress_nums');
        if (!empty($procedureProgressNums) && $procedureProgressNums >= $this->warningThreshold) {
            // 发送报警信息
            $msgCenter = new MsgCenter();
            $msgCenter->sendSubgroupProductMessage("redis中记录的切割子分组进程数过多","redis中记录的切割子分组进程数过多，现已{$procedureProgressNums}个，告警阀值为".$this->warningThreshold);  
        }
    }
    
    /*
     * 对超过分组发送完成时间仍未发完的分组进行监控
     * 规则：1.对发送方式为【推送】的【启动】状态分组
     *        以分组最新启动时间起18小时后，该分组仍处于【发送中】状态。
     *      2.对发送方式为【X天发送】的【启动】状态且未执行过暂停操作的分组：
     *        以分组启动时间起，{X天}*24小时 后，该分组仍处于【发送中】状态
     *      3.对已启动但【未发送】状态的分组：
     *        以分组最新启动时间起6小时后，该分组仍处于【未发送】状态。
     *      注：暂停操作从发送管理操作日志获取。
     * 
     * @return boolen
     */
    public function actionMonitorExceptionGroup() {
        
        ignore_user_abort(true);     // 忽略用户的中断
        set_time_limit(0);
        
        $curTime = time();
        
        $pushGroupMonitorTime = 10*3600; // 推送方式的分组在开启后10小时进行监控
        $daysSendGroupMonitorTime = 24*3600; // X天发送的{X天}*24小时
        $noSendGroupMonitorTime = 3*3600;  // 已启动但【未发送】状态分组在最新启动时间起3小时后监控
        
        $mailGroupModel = new MailGroup;
        
        // 要修改的字段
        $updateData = [
            'is_send_exception'   => 1
        ];
        
        // 直接推送修改条件
        $updateExceptionGroupConditon = [
            'send_mode' => 2,
            'state'     => 1,
            'group_last_send' => ['>' => 0],
            'join_string' => ' ((start_time > 0 and start_time < '.($curTime-$pushGroupMonitorTime).') or (start_time = 0 and boot_time < '.($curTime-$pushGroupMonitorTime).')) '
        ];
        
        // 几天发送的分组修改条件
        $updateDaysExceptionGroupConditon = [
            'send_mode' => 1,
            'state'     => 1,
            'send_type' => ['>' => 0],
            'group_last_send' => ['>' => 0],
            'join_string' => ' ((start_time > 0 and start_time < '.($curTime.'-send_type*'.$daysSendGroupMonitorTime).') or (start_time = 0 and boot_time < '.($curTime.'-send_type*'.$daysSendGroupMonitorTime).')) '
        ];
        
        // 7天发送的分组修改条件
        $update7daysExceptionGroupConditon = [
            'send_mode' => 1,
            'state'     => 1,
            'send_type' => 0,
            'group_last_send' => ['>' => 0],
            'join_string' => ' ((start_time > 0 and start_time < '.($curTime-7*$daysSendGroupMonitorTime).') or (start_time = 0 and boot_time < '.($curTime-7*$daysSendGroupMonitorTime).')) '
        ];
        
        // 已启动6小时后但【未发送】状态的分组修改条件
        $updateNoSendGroupCondition = [
           'state'     => 1,
           'group_last_send'    => 0,
           'join_string' => ' ((start_time > 0 and start_time < '.($curTime-$noSendGroupMonitorTime).') or (start_time = 0 and boot_time < '.($curTime-$noSendGroupMonitorTime).')) ' 
        ];
        
        $updateNoSendData = [
            'is_send_exception'   => 2
        ];
        
        $mailGroupModel->updateGroupByCondition($updateNoSendGroupCondition,$updateNoSendData);
        
        $mailGroupModel->updateGroupByCondition($updateExceptionGroupConditon,$updateData);
        
        $updateDaysRes = $mailGroupModel->updateGroupByCondition($updateDaysExceptionGroupConditon,$updateData);
        
        $update7DaysRes = $mailGroupModel->updateGroupByCondition($update7daysExceptionGroupConditon,$updateData);
        
        if($updateDaysRes || $update7DaysRes) {
            
            // 将几天发送有暂停的分组且已经置为异常的分组更改为正常分组
            $suspendGroupCondition = [
                'send_mode' => 1,
                'is_send_exception'   => 1
            ];

            $suspendUpdateData = [
                'is_send_exception'   => 0
            ];
            $mailGroupModel->updateSuspendGroupByCondition($suspendGroupCondition,$suspendUpdateData);
            
        }
        
        $exceptionGroupIds = [];
        
        // 从分组表获取异常分组发送给相关人员
        $exceptionGroups = $mailGroupModel->getNoSendExceptionGroups();
        
        $msgCenter = new MsgCenter();
        $site = new \app\components\Site();
        
        foreach($exceptionGroups as $exceptionGroup) {
            
            $exceptionGroupIds[] = $exceptionGroup['group_id'];
            $siteName = $site->getSiteShortNameById($exceptionGroup['site_id']); // 站点名称
            $sendType = $exceptionGroup['send_mode'] == 2 ? '推送' : ($exceptionGroup['send_mode'] == 1 && $exceptionGroup['send_type'] == 0 ? '7天发送' : $exceptionGroup['send_type'].'天发送'); // 发送方式
            
//            if ($exceptionGroup['channel_id'] == 2 || $exceptionGroup['channel_id'] == 6) {
//                $exceptionGroup['send_status_ok_count'] = $exceptionGroup['send_ok_count'] - $exceptionGroup['send_status_fail_count'];
//            }
            if(!$exceptionGroup['total_count']) {
                $sendOkRate = 0;
            } else {
                $sendOkRate = number_format( $exceptionGroup['send_ok_count'] / $exceptionGroup['total_count'] , 4)*100;
            }
            
            $dealData['site_id'] = 99; // 发送人员为EMP所属人员
            $dealData['title'] = "EMP营销邮件，{$siteName}站【{$exceptionGroup['template_type_name']}】的分组（ID）【{$exceptionGroup['group_id']}】，未及时完成发送";
            
            
            
            $dealData['exceptionEmailTemplateContent'] = "EMP营销邮件，{$siteName}站【{$exceptionGroup['template_type_name']}】且发送方式【{$sendType}】的分组（ID）【{$exceptionGroup['group_id']}】，计划推送数【{$exceptionGroup['total_count']}】、推送完成率【{$sendOkRate}%】，未推送量【".($exceptionGroup['total_count']-$exceptionGroup['send_ok_count'])."】";
        
            $dealData['exceptionWechatTemplateContent'] = "EMP营销邮件，{$siteName}站【{$exceptionGroup['template_type_name']}】且发送方式【{$sendType}】的分组（ID）【{$exceptionGroup['group_id']}】，计划推送数【{$exceptionGroup['total_count']}】、推送完成率【{$sendOkRate}%】，未推送量【".($exceptionGroup['total_count']-$exceptionGroup['send_ok_count'])."】";
            
            $msgCenter->go_msgcenter($dealData); 
            
        }
        
        // 修改已经发送异常分组的字段为已发送
        if($exceptionGroupIds) {
            $mailGroupModel->updateGroupsByGroupIds($exceptionGroupIds,array('exception_id_send' => 1));
        }
        
    }
    
}